/*
 * File    : /modules/authorition.js
 * Time    : 2021-04-03 18:34:56
 * Author  : Gray Snail
 * Version : 1.0
 * Contact : shtao2011@sina.com
 * License : Copyright (c) 2021 Gray Snail
 * Desc    : 全局的权限认证
 */

const acl = require('acl')

const aclInstance = new acl(new acl.memoryBackend())
const PermService = require('../services/PermisionService')
const UserService = require('../services/UserService')

/**
 * 初始化角色权限
 */
module.exports.initial = async function () {
  // 数据获取 perms（role）
  // url分割，perms 为*,否则 split by ','
  // aclInstance.allow( roles, resources, permissions, function(err) )
  // addUserRoles( userId, roles, function(err))

  const perms = await PermService.rolePerms()
  perms.forEach((item) => {
    const perm = item.perm
    if (!perm.url || !perm.perms) return

    const resours = perm.url.split(',')
    const perm_str = perm.perms || ''
    let item_perms = null
    if (item.type === 1) {
      item_perms = perm_str === '*' ? ['get', 'post', 'put', 'delete'] : perm_str.split(',')
    } else {
      item_perms = ['get']
    }
    aclInstance.allow(perm.roleId, resours, item)
  })

  const users = await UserService.userRoles()
  users.forEach((user) => {
    console.log(user)
    aclInstance.addUserRoles(
      user.id,
      user.roleIDs.map((role) => {
        return role.role_id
      })
    )
  })
}

module.exports.isAllow = async function (userId, resource, perm) {
  return new Promise((resolve, reject) => {
    aclInstance.isAllowed(userId, resource, perm, (err, allowed) => {
      if (err) {
        reject(err)
      }
      resolve(allowed)
    })
  })
}

/**
 * 用户拥有的权限
 * @param {String} userId
 */
module.exports.userRoles = async function (userId) {
  return new Promise((resolve, reject) => {
    aclInstance.userRoles(userId, (err, roles) => {
      if (err) reject(err)
      resolve(roles)
    })
  })
}

module.exports.addUserRoles = async function () {}

module.exports.removeUserRoles = async function () {}

module.exports.hasRole = async function () {}

module.exports.allow = async function () {}

module.exports.rmAllow = async function () {}
